package com.crazyhat.crazyhat.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crazyhat.crazyhat.anno.AdminOnly;
import com.crazyhat.crazyhat.attribute.ClubStatusEnum;
import com.crazyhat.crazyhat.dto.ClubApprovalDTO;
import com.crazyhat.crazyhat.dto.ClubApprovalDetailDTO;
import com.crazyhat.crazyhat.dto.ClubDetailsDTO;
import com.crazyhat.crazyhat.dto.ClubManagementDTO;
import com.crazyhat.crazyhat.dto.ClubUpdateRequestDTO;
import com.crazyhat.crazyhat.dto.CreateClubDTO;
import com.crazyhat.crazyhat.entity.Club;
import com.crazyhat.crazyhat.entity.Participation;
import com.crazyhat.crazyhat.entity.User;
import com.crazyhat.crazyhat.pojo.Result;
import com.crazyhat.crazyhat.service.IClubService;
import com.crazyhat.crazyhat.utils.ScanImage;
import com.fasterxml.jackson.core.JsonProcessingException;


/**
 * <p>
 * 社团 前端控制器
 * </p>
 *
 * @author crazyhat
 * @since 2024-07-05
 */
@RestController
@RequestMapping("/club")
public class ClubController {

    @Autowired
    private IClubService clubService;

    /**
     * 获取社团详情信息，前端用户使用
     * @param clubId
     * @return
     */
    @PostMapping("/clubInfo")
    public Result<Club> getClubInfo(@RequestParam(value = "clubId") Integer clubId) {

        Club club =clubService.getClubInfo(clubId);

        if (club!=null) {
            return Result.success(club);
        } else {
            return Result.error("获取社团详情失败");
        }
    }

    /**
     * 创建新社团
     * @param club
     * @return
     */
    @PostMapping(value ="/createNewClub", consumes = "multipart/form-data")
    public Result createNewClub(
            @ModelAttribute @Validated CreateClubDTO createClubDTO
    ){

        boolean isNormalImage=true;
        if (createClubDTO.getLogoPicture()!=null&&(!(createClubDTO.getLogoPicture().isEmpty()))) {
            isNormalImage=ScanImage.scanAndApprove(createClubDTO.getLogoPicture(),true);
        }

        if (!isNormalImage) {
            return Result.error("logo图片违规");
        }

        Club club=clubService.createNewClub(createClubDTO);

        if (club!=null) {
            return Result.success(club);
        } else {
            return Result.error("创建社团失败");
        }
    }

    /**
     * 社团管理所需信息
     * @param
     * @return
     */
    @AdminOnly
    @GetMapping("/management")
    public Result getClubManagementInfo() {
        List<ClubManagementDTO> clubs = clubService.getClubManagementInfo();
        return Result.success(clubs);
    }

    //社团管理
    //删除社团发送一个要删除的社团的ID数组
    @AdminOnly
    @DeleteMapping("/delete")
    public Result deleteClubs(@RequestBody List<Integer> clubIds) {

        boolean success = clubService.deleteClubs(clubIds);
        if (success) {
            return Result.success("社团删除成功");
        } else {
            return Result.error("社团删除失败");
        }
    }

    /**
     * 社团管理，
     * 查看社团详情，包括所有社团成员，
     * 仅系统管理员使用
     * @param clubId
     * @return
     */
    @AdminOnly
    @GetMapping("/details/{clubId}")
    public Result getClubDetails(@PathVariable Integer clubId) {
        ClubDetailsDTO clubDetails = clubService.getClubDetails(clubId);
        if (clubDetails != null) {
            return Result.success(clubDetails);
        } else {
            return Result.error("没有找到该社团");
        }
    }

    /**
     * 社团管理 用户管理
     * @param payload
     * @return
     * @throws JsonProcessingException
     */
    @AdminOnly
    @PostMapping("/updateMemberPosition")
    public Result updateMemberPosition(@RequestBody Map<String, Object> payload) throws JsonProcessingException {
        Integer clubId = (Integer) payload.get("clubId");
        Integer studentId = (Integer) payload.get("studentId");
        String position = (String) payload.get("position");
        boolean success = clubService.updateMemberPosition(clubId, studentId, position);
        if (success) {
            return Result.success("职位更新成功");
        } else {
            return Result.error("职位更新失败");
        }
    }


    /**
     * 社团管理，查询用户
     * @param clubId
     * @param keyword
     * @return
     */
    @AdminOnly
    @GetMapping("/searchMember")
    public Result searchMember(@RequestParam Integer clubId, @RequestParam String keyword) {
        List<ClubDetailsDTO.MemberInfo> members = clubService.searchMember(clubId, keyword);
        return members != null && !members.isEmpty() ? Result.success(members) : Result.error("没有找到该成员");
    }

    /**
     * 获取所有审核中的社团信息
     *
     * @return 审核中的社团列表
     */
    @AdminOnly
    @GetMapping("/inReview")
    public Result<List<ClubApprovalDTO>> getClubsInReview() {
        List<ClubApprovalDTO> clubsInReview = clubService.getClubsInReview();
        return Result.success(clubsInReview);
    }

    /**
     * 获取所有创建申请已通过的社团
     * @return
     */
    @AdminOnly
    @GetMapping("/approved")
    public Result<List<ClubApprovalDTO>> getApprovedClubs() {
        List<ClubApprovalDTO> approvedClubs = clubService.getApprovedClubs();
        return Result.success(approvedClubs);
    }

    /**
     * 获取所有创建申请被拒绝的社团
     * @return
     */
    @AdminOnly
    @GetMapping("/rejected")
    public Result<List<ClubApprovalDTO>> getRejectedClubs() {
        List<ClubApprovalDTO> rejectedClubs = clubService.getRejectedClubs();
        return Result.success(rejectedClubs);
    }

    /**
     * 获取社团的详细信息，不包括社团成员信息
     * @param clubId
     * @return
     */
    @AdminOnly
    @GetMapping("/approvalDetails/{clubId}")
    public Result<ClubApprovalDetailDTO> getClubApprovalDetails(@PathVariable Integer clubId) {
        ClubApprovalDetailDTO details = clubService.getClubApprovalDetails(clubId);
        return details != null ? Result.success(details) : Result.error("没有找到该社团");
    }

    /**
     * 更新社团审核
     * @param clubId
     * @param approve
     * @return
     */
    @AdminOnly
    @PostMapping("/updateStatus")
    public Result updateClubStatus(@RequestParam Integer clubId, @RequestParam boolean approve) {
    String message = "";
    ClubStatusEnum status = approve ? ClubStatusEnum.Open : ClubStatusEnum.Rejected;
    boolean success = clubService.updateClubStatus(clubId, status);
    if(success){
        message = approve ? "社团创建申请同意成功" : "社团创建申请拒绝成功";
    }
    return success ? Result.success(message) : Result.error(message);
}


    /**
    * 修改社团信息
    * */
    @PutMapping( "/updateClubInfo")
    public Result updateClub(@Validated @RequestBody ClubUpdateRequestDTO updateRequest) {
        Club club= clubService.updateClubInfo(updateRequest.getClubId(), updateRequest);
        if (club!=null) {
            return Result.success(club);
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 修改社团logo
     * */
    @PutMapping(value = "/changeLogo",consumes = "multipart/form-data")
    public Result changeLogo(MultipartFile logo,int clubId){

        if (logo==null||logo.isEmpty()) {
            return Result.error("图片不能为空");
        }
        
        boolean isNormalImage=true;
        isNormalImage=ScanImage.scanAndApprove(logo,true);

        if (!isNormalImage) {
            return Result.error("上传的图片违规");
        }

        String result=clubService.changeLogo(logo,clubId);
        return Result.success(result);
    }

    /**
     * 手动更新社团热度
     * @return 操作结果
     */
    @AdminOnly
    @PostMapping("/updatePopularity")
    public Result updateClubPopularity() {
        clubService.updateClubPopularity();
        return Result.success("社团热度更新成功");
    }

    /**
     * 一把手删除社团
     * */
    @PostMapping("/deleteClub")
    public Result deleteClub(@RequestParam int clubId) {
        boolean success=clubService.deleteClub(clubId);
        if(success)
            return Result.success("社团已删除");
        else
            return Result.error("删除失败");
    }
    /*
    * 更换一把手
    * */
    @PostMapping("/changeLeader")
    public Result changeLeader(@RequestParam int newLeaderId,@RequestParam int clubId) {
        User user=clubService.changeLeader(newLeaderId,clubId);
        if(user!=null)
            return Result.success("新一把手的学号："+user.getStudentId());
        else
            return Result.error("更换失败");
    }

    /*
    * 一把手踢人
    * */
    @PostMapping("/kick")
    public Result kick(@RequestParam int userId,@RequestParam int clubId){
        boolean result=clubService.kick(userId,clubId);
        if(result){
            return Result.success(result);
        }
        return Result.error("未能成功踢出");
    }

    /*
    * 浏览社团
    * */
    @GetMapping("/browseClubs")
    public Result<Page<Club>> browseClubs(@RequestParam int pageNum,@RequestParam String clubCategory){
        Page<Club> clubs=clubService.browseClubs(pageNum,clubCategory);
        return Result.success(clubs);
    }

    /**
     * 退出社团
     */
    @PostMapping("/quitClub")
    public Result quitClub(@RequestParam int clubId) throws JsonProcessingException {
        boolean result =clubService.quitClub(clubId);
        return Result.success(result);
    }
    /**
     * 调整人员职位
     */
    @PostMapping("/memberToSecondLeader")
    public Result memberToSecondLeader(@RequestParam int clubId,@RequestParam int memberId) throws JsonProcessingException {
        Participation participation=clubService.memberToSecondLeader(clubId,memberId);
        if(participation==null){
            return Result.error("职务调整失败");
        }
        return Result.success(participation);
    }

    /**
     * 调整人员职位
     */
    @PostMapping("/secondLeaderToMember")
    public Result secondLeaderToMember(@RequestParam int clubId,@RequestParam int memberId) throws JsonProcessingException {
        Participation participation=clubService.secondLeaderToMember(clubId,memberId);
        if(participation==null){
            return Result.error("职务调整失败");
        }
        return Result.success(participation);
    }
}
